package client.ui;

import java.util.ArrayList;
import java.util.List;

import phasebook.client.msgs.MessageInfo;
import phasebook.client.msgs.UserProfileInfo;
import client.Controller;
import client.Controller.ResponseHandler;
import client.api.CombinedResponse;

import com.google.gwt.i18n.shared.DateTimeFormat;
import com.google.gwt.i18n.shared.DateTimeFormat.PredefinedFormat;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ImageStyle;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.widgets.HTMLPane;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.layout.VLayout;

public class BoardSection extends SectionStackSection implements ResponseHandler{
	private UserProfileInfo owner;
	private VLayout layout = new VLayout();
	public BoardSection(Controller controller,UserProfileInfo owner){
		super("Message Board");
		this.owner = owner;
		super.setExpanded(true);
		super.setCanCollapse(false);
		layout.setHeight("80%");
		layout.setOverflow(Overflow.AUTO);
		super.addItem(layout);
		
		controller.addResponseHandler(this);
	}

	@Override
	public void onResponse(CombinedResponse response) {
		List<MessageInfo> messages = response.getMessages();
		if (messages!=null){
			ArrayList<Post> posts = new ArrayList<Post>();
			for(MessageInfo msg:messages)
				if (msg.getBoardOwner().getUserId()==owner.getUserId())
					posts.add(0,new Post(msg));
			if (posts.size()>0){
				layout.setMembers(posts.toArray(new Post[posts.size()]));
				HTMLPane emptySpace = new HTMLPane();
				emptySpace.setWidth100();
				emptySpace.setHeight100();
				emptySpace.setOverflow(Overflow.CLIP_V);
				layout.addMember(emptySpace);
			}
		}
	}
	
	
	public class Post extends VLayout{
		public Post(MessageInfo msg){
			super.setWidth100();
			super.setOverflow(Overflow.VISIBLE);
			if (msg.isPrivate())
				super.setBackgroundColor("#FAD7D7");//light red
			else
				super.setBackgroundColor("#D7FAE4");//light green
			
			HTMLPane msg_html = new HTMLPane();
			msg_html.setWidth100();
			msg_html.setOverflow(Overflow.VISIBLE);
			msg_html.setContents(msg.getMessageText());
			
			Label timeLabel = new Label(msg.getPublisher().getName() +
				" @ " +DateTimeFormat.getFormat(PredefinedFormat.RFC_2822).format(msg.getTimestamp()));
			timeLabel.setAlign(Alignment.RIGHT);
			timeLabel.setWidth100();
			timeLabel.setHeight("1%");
			timeLabel.setOverflow(Overflow.VISIBLE);
			
			HLayout hLayout = new HLayout();
			hLayout.addMember(msg_html);
			super.addMember(hLayout);
			
			super.addMember(timeLabel);
			
			if (msg.getPhoto()!=null){
				Img img = new Img("image?id="+msg.getPhoto().getPhotoId(),320,180);
				img.setImageType(ImageStyle.STRETCH);
				hLayout.addMember(img);
			}
		}
	}
}
